const express = require('express');
const path = require('path');
const cookieparser = require('cookie-parser');
const multer = require('multer');
const bodyParser = require('body-parser');
const base = require(path.join(__dirname, './base'));
const plugService = require(path.join(__dirname,'./../service/plugservice'));
const funcService = require(path.join(__dirname,'./../service/funcservice'));
let router = express.Router(); 

router.get('/get', async function (req, res) {
    let param = req.query;
    let data = await plugService.queryPlug(param).catch(
        err => {
            console.log(JSON.stringify(err));
        });
    let datares = JSON.parse(JSON.stringify(data));
    /**封装功能列表---因为要深拷贝，代码比较啰嗦 */
    if(param.id!="" && typeof(param.id)!="undefined"){
        let funcprm = await funcService.queryFunc({plugid:param.id}).catch(
            err => {
                console.log(JSON.stringify(err));
            });
        let funcdata = JSON.parse(JSON.stringify(funcprm));
        let rtdata = datares.data[0];
        rtdata.function = funcdata.data;
        datares.data[0]=rtdata;
    }
    base.send(res,datares);
});

router.post('/save', bodyParser.json(), async function (req, res) {
    let param = req.body;
    // console.log("params:"+JSON.stringify(req.params));
    // console.log("body:"+JSON.stringify(req.body));
    // console.log("query:"+JSON.stringify(req.query));
    let data = await plugService.savePlug(param).catch(
        err => {
            console.log(JSON.stringify(err))
        });
    base.send(res,data);
});

router.put('/update',bodyParser.json(), async function (req, res) {
    let param = req.body;
    let data = await plugService.updatePlug(param).catch(
        err => {
            console.log(JSON.stringify(err))
        });
    base.send(res,data);
});

router.delete('/delete', async function (req, res) {
    let param = req.query;
    let data = await plugService.deletePlug(param).catch(
        err => {
            console.log(JSON.stringify(err))
        });
    base.send(res,data);
});

//导出该路由
module.exports = router;